package top.haijunit.mark.common.core.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

/**
 * @Author 百旺张
 * @Date 2021/11/11
 * @description
 */
@Slf4j
@UtilityClass
public class JwtUtil {

    // token有效时长
    private static final long tokenExpiration = 24 * 60 * 60 * 1000;
    // 编码秘钥
    private static final String tokenSignKey = "1q@w3e";

    public static final String tokenName = "token";

    /** 创建token */
    public String createToken(String username) {
        return createToken(username, null);
    }
    /** 创建token */
    public static String createToken(String username, Map<String, Object> claims) {
        return Jwts.builder().setSubject(username)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
    }
    /** 获取token中的username */
    public String getUsernameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if(claims.getExpiration().before(new Date())){
            return null;
        }
        String username = claims.getSubject();
        if (StrUtil.isNotBlank(username)) {
            return username;
        }
        return Convert.toStr(claims.get("username"), null);
    }
    /** 判断token是否再有效期之内 */
    public Boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    private Claims getClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
    }
    /** 刷新token */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return createToken(claims.getSubject(), claims);
    }
}
